package com.oocl.command;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.text.ParseException;

import com.oocl.client.ClientInfoList;

public class CommandHandle {
	private static BufferedReader br;
	private static OutputStream out;
	private static Socket socket;
	
	public CommandHandle(BufferedReader br, OutputStream out, Socket socket) {
		super();
		this.br = br;
		this.out = out;
		this.socket = socket;
	}
	
	public void handleCommandFromTcpClient(String line) throws IOException, ParseException {
		//String line = br.readLine();
		if (line.equals("Q")) {
			ClientInfoList cInfoList = new ClientInfoList(socket);
			cInfoList.deleteClientInfo();
			
			br.close();
			out.close();
		}
		SemanticError semanticError = new SemanticError(line);
		if (line.startsWith("A")) {
			
			if (!semanticError.isAddError()) {
				Add add = new Add(line, out);
				if (line.startsWith("A-P")) {
					add.addPerson();
				}
				if (line.startsWith("A-D")) {
					add.addDept();
				}
			} else {
				out.write("Add semantic error. Please try again or quit.\n".getBytes());
				out.write("over\n".getBytes());
			}
		}
		else if (line.startsWith("U")) {
			if (!semanticError.isUpdateError()) {
				Update update = new Update(line, out);
				if (line.startsWith("U-P")) {
					update.updatePerson();
				}
				if (line.startsWith("U-D")) {
					update.updateDept();
				}
			} else {
				out.write("Update semantic error. Please try again or quit.\n".getBytes());
				out.write("over\n".getBytes());
			}
		}
		else if (line.startsWith("D")) {
			if (!semanticError.isDeleteError()) {
				Delete delete = new Delete(line, out);
				if (line.startsWith("D-P")) {
					delete.deletePerson();
				}
				if (line.startsWith("D-D")) {
					delete.deleteDept();
				}
			} else {
				out.write("Delete semantic error. Please try again or quit.\n".getBytes());
				out.write("over\n".getBytes());
			}
		}
		else if (line.startsWith("L")) {
			if (!semanticError.isQueryError()) {
				Query query = new Query(line, out);
				if (line.startsWith("L-PA")) {
					query.QueryPersonALL();
				}
				if (line.startsWith("L-DA")) {
					query.QueryDeptALL();
				}
				if (line.startsWith("L-PD")) {
					query.QueryPerDept();
				}
			} else {
				out.write("Query semantic error. Please try again or quit.\n".getBytes());
				out.write("over\n".getBytes());
			}
		}
	}
	
}
